#!/usr/bin/perl

use strict;
use warnings;
use Flickr::Upload;

if(@ARGV < 2){
	print "useage: flickpr.pl <gallery path> <recursion>\n";
	exit 1;
}

my $version = '0.1.0';
my $ua = Flickr::Upload->new({'key' => '2b590eb400d8917457f67e76307d38ff', 'secret' => '7b6ded3bafd19cc3'});

my @photos;
my $gallery_path = shift;
my $recursion = int(shift);

print "path: $gallery_path\nscaning all photos and cache them...\n";
&cachePhotoList($gallery_path, $recursion);
#print join("\n",@photos), "\n";

print "photos: $#photos, uploading...\n";

for(@photos){
	print "上传：$_";
	$ua->upload(
		'photo' => $_,
		'auth_token' => '2016869-b551856c23820871',
		'tags' => &autoTags($_),
		'is_public' => 1,
		'is_friend' => 1,
		'is_family' => 1
	) or die "\tFailed to upload $_.\n";
	#print &autoTags($_);
	print "\t successed.\n";
}

#自动根据文件名加tags
#可以考虑使用hash来缓存图片
#在缓存的同时，把目录名也存储到图片
#数据里作为tag之一在上传时赋值
sub autoTags {
	my $p = shift;
	my $t = '';
	my @t;
	$t = $1 if $p =~ /.*\/(.*)\.[a-zA-Z0-9]+/ig;
	$t =~ s/(_|\-)/ /ig;
	return $t;
}

#缓存所有图片，不带后缀名识别
sub cachePhotoList {
	my ($path, $r, $DIR) = @_;
	if(chdir($path)){
		opendir $DIR, $path or die "$!";
		while(my $p = readdir($DIR)){
			if($p ne '.' and $p ne '..'){
				if(chdir("$path/$p") and $r){
					&cachePhotoList("$path/$p", $r);
				}else{
					push @photos, "$path/$p" unless -d "$path/$p";
				}
			}
		}
		closedir($DIR);
	}
}
